﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XNOgre.Core;

namespace XNOgre.Graphics
{
    public static class MeshHelper
    {
        public static RenderOperation CreateQuad(Vector3 origin, Vector3 normal, Vector3 up, float width, float height)
        {
            var Vertices = new VertexPositionNormalTexture[4];
            var Index = new short[6];

            var left = Vector3.Cross(normal, up);
            var upperCenter = (up * height / 2) + origin;
            var upperLeft = upperCenter + (left * width / 2);
            var upperRight = upperCenter - (left * width / 2);
            var lowerLeft = upperLeft - (up * height);
            var lowerRight = upperRight - (up * height);

            Vector2 textureUpperLeft = new Vector2(0, 0);
            Vector2 textureUpperRight = new Vector2(1f, 0f);
            Vector2 textureLowerLeft = new Vector2(0, 1f);
            Vector2 textureLowerRight = new Vector2(1f, 1f);

            for (int i = 0; i < Vertices.Length; i++)
            {
                Vertices[i].Normal = normal;
            }

            Vertices[0].Position = lowerLeft;
            Vertices[0].TextureCoordinate = textureLowerLeft;

            Vertices[1].Position = upperLeft;
            Vertices[1].TextureCoordinate = textureUpperLeft;

            Vertices[2].Position = lowerRight;
            Vertices[2].TextureCoordinate = textureLowerRight;

            Vertices[3].Position = upperRight;
            Vertices[3].TextureCoordinate = textureUpperRight;

            Index[0] = 0;
            Index[1] = 1;
            Index[2] = 2;
            Index[3] = 2;
            Index[4] = 1;
            Index[5] = 3;

            var rop = new RenderOperation();
            rop.IndexData = new IndexBuffer(Root.Instance.RenderSystem.GraphicsDevice, typeof(short), Index.Length, BufferUsage.None);
            rop.IndexData.SetData(Index);
            rop.VertexData = new VertexBuffer(Root.Instance.RenderSystem.GraphicsDevice, typeof(VertexPositionNormalTexture), Vertices.Length, BufferUsage.None);
            rop.VertexData.SetData<VertexPositionNormalTexture>(Vertices);

            rop.OperationType = PrimitiveType.TriangleList;
            rop.VertexCount = Vertices.Length;
            rop.PrimCount = 2;
            return rop;
        }

    }
}
